package com.irdstudio.tdp.console.utils;

import java.util.Map;

/**
 * 用于框架中数据转换为JSON格式的处理
 * @author ligm
 */
public class JsonUtil {

	/* JSON起始标记 */
	public static final String BEGIN_TAG = "{";
	/* JSON结束标记 */
	public static final String END_TAG = "}";
	/* JSON内容符号-双引号 */
	public static final String CONTENT_TAG = "\"";
	/* JSON键值分隔符 */
	public static final String KV_SPLIT = ":";
	/* JSON单元分隔符 */
	public static final String CELL_SPLIT = ",";
	/* JSON多条记录开始标记 */
	public static final String MULTI_BEGIN = "[";
	/* JSON多条记录结束标记 */
	public static final String MULTI_END = "]";



	/**
	 * 将Map对象转换为JSON字符串
	 * @param dataRowMap
	 * @param isJsonClosed 是否封闭(封闭的话，则字符串前后有{})
	 * @return
	 */
	public final static StringBuffer makeJsonContent(Map<String, Object> dataMap,
			boolean isJsonClosed) {
		StringBuffer sb = new StringBuffer();
		if (isJsonClosed)
			sb.append(BEGIN_TAG);
		for (Map.Entry<String, Object> stringObjectEntry : dataMap.entrySet()) {
			String key = stringObjectEntry.getKey();
			sb.append(CONTENT_TAG).append(key.toUpperCase()).append(CONTENT_TAG);
			sb.append(KV_SPLIT);
			sb.append(CONTENT_TAG).append(stringObjectEntry.getValue()).append(CONTENT_TAG);
			sb.append(CELL_SPLIT);
		}
		if (sb.length() > 1)
			sb.deleteCharAt(sb.length() - 1);
		if (isJsonClosed)
			sb.append(END_TAG);
		return sb;
	}
	
	/** 
     * JSON字符串特殊字符处理，比如：“\A1;1300” 
     * @param s 
     * @return String 
     */  
	public final static String formatJson(String s) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < s.length(); i++) {
			char c = s.charAt(i);
			switch (c) {
//			case '\"':
//				sb.append("\\\"");
//				break;
//			case '\\':
//				sb.append("\\\\");
//				break;
			case '/':
				sb.append("\\/");
				break;
			case '\b':
				sb.append("\\b");
				break;
			case '\f':
				sb.append("\\f");
				break;
			case '\n':
				sb.append("\\n");
				break;
			case '\r':
				sb.append("\\r");
				break;
			case '\t':
				sb.append("\\t");
				break;
			default:
				sb.append(c);
			}
		}
		return sb.toString();
	}
}